package com.android.volley.cookies;

import android.content.Context;

import java.util.List;

/**
 * Created by ChameleonChen
 */
public class CookiesManager {

    /** set true value when CookiesManager has been instantiated */
    private boolean hasInit = false;

    private static CookiesManager instance = null;

    private Context context;

    private OnCookiesDataChangedListener onCookiesDataChangedListener;

    public static boolean hasInit() {
        if (instance == null)
            return false;

        return instance.hasInit;
    }

    /**
     * If you want volley to support cookies, you must invoke this method to init cookies manager.
     * @param context
     * @param listener  you must implement this listener to define how to deal with the cookie data.
     */
    public static void initCookiesManager(Context context, OnCookiesDataChangedListener listener) {
        if (context == null || listener == null)
            throw new NullPointerException();

        if (instance != null)
            throw new IllegalStateException("cookies manager has already init");

        instance = new CookiesManager(context, listener);
    }

    private CookiesManager(Context context, OnCookiesDataChangedListener listener) {
        this.context = context;
        this.onCookiesDataChangedListener = listener;

        hasInit = true;
    }

    /**
     * saving the Cookies.
     * You must invoke {@link #initCookiesManager(Context, OnCookiesDataChangedListener)} method
     * before invoke this method, otherwise, this method will has no effects.
     * @param cookies
     */
    public static void saveCookies(List<Cookie> cookies) {
        if (instance == null)
            return ;

        instance.onCookiesDataChangedListener.saveCookies(cookies);
    }

    /**
     * saving the Cookies.
     * You must invoke {@link #initCookiesManager(Context, OnCookiesDataChangedListener)} method
     * before invoke this method, otherwise, this method will has no effects.
     * @param url
     */
    public static String getCookiesHeader(String url) {
        if (instance == null)
            return null;

        return instance.onCookiesDataChangedListener.getCookiesHeader(url);
    }
}